/* 
 * File:   main.c
 * Author: Mr A. Doministrateur
 *
 * Created on 7 mars 2012, 15:37
 */
#include <stdio.h>

#include "../Util/config.h"
#include "SensorCom.h"
#include "../Util/comAPI.h"
#include "../Util/lienSerieMC.h"

#ifdef __DEBUG
    #pragma config WDTEN = OFF
    #pragma config LVP = OFF
#else
    #pragma config WDTEN = SWON     // Watchdog Timer Enable bits (WDT is controlled by SWDTEN bit of the WDTCON register)
    #pragma config WDTPS = 256       // Watchdog Timer Postscale Select bits (1:32)
#endif

#define BUTTON_REGISTER_UNREGISTER PORTAbits.RA3
extern char gl_Registered;

void sleepMode(char sleepCount);

void main (void)
{
    // INITIALISATION
    TRISAbits.RA3 = 1;
    ANSELAbits.ANSA3 = 0;
    
    init_MicroController();
    initSensor();
    initLed();

    eteindreLed(-1);

    // LED 0 : ON
    allumerLed(ALL_LED);
    
    // REGISTER AND SYNCHRONISATION
    while(BUTTON_REGISTER_UNREGISTER != 0);

    registerDevice();

    if (getTimeToSleep() < getSleepPeriod())
    {
        sleepMode(getSleepPeriod() - getTimeToSleep());
        setTimeToSleep(getSleepPeriod());
    }
    else
    {
        setTimeToSleep(getTimeToSleep());
    }

    // LED 0 : OFF
    eteindreLed(ALL_LED);

    while(1)
    {
//         DEVICE WAKE UP
        allumerLed(2);
        setWatchDog(getTimeToSleep(), WD_COORD_SENSOR_APPLI);

//        // Waiting for commands
        while((getTimeLeft(WD_COORD_SENSOR_APPLI) > getSleepPeriod())&&(BUTTON_REGISTER_UNREGISTER != 0))
        {
            if(recept(1) != 0)
                handleDataPacket();
        }
        if (BUTTON_REGISTER_UNREGISTER == 0)
        {
            unregisterDevice();
            allumerLed(ALL_LED);
            while(1);
        }
//         DEVICE IN SLEEP MODE
        eteindreLed(2);
        sleepMode(getTimeLeft(WD_COORD_SENSOR_APPLI));
        setTimeToSleep(2*getSleepPeriod());
    }
}

void sleepMode(char sleepCount)
{
    while(sleepCount > 0)
    {
        sleepCount --;
        WDTCONbits.SWDTEN = 1;
        ClrWdt();
        Sleep();
        Nop();
        WDTCONbits.SWDTEN = 0;
    }
}
